const userService = require('../../../services/dao/app/user');
const thirdLoginService = require('../../../services/dao/common/thirdLogin');

const sessionFilter = require('../../../middlewares/clientSessionMiddleware');
const log4js = require('../../../utils/log4js');
const IP2Region = require('ip2region');
const query = new IP2Region();

const $ = module.exports;

// 密码登录
$.get_login = (req, res) => {
    let {mobile, password} = req.query;
    userService.loginPassword(mobile, password).then((data) => {
        req.session.client_login_info = data;

        let update_time = helper.now();
        let client_ip = helper.getClientIP(req);
        let client_ip_address = '';
        if (client_ip) {
            const res = query.search(client_ip) || {province: '', city: ''};
            client_ip_address = `${res.province ? res.province : ''} ${res.city}`;
        }

        db().md_user.update({
            last_login_time: update_time,
            last_client_ip: client_ip,
            last_client_ip_address: client_ip_address,
        }, {where: {id: data.id}});
        db().md_user_login_log.create({
            id: helper.uuid(),
            user_id: data.id,
            client_ip: client_ip,
            client_ip_address: client_ip_address,
        });

        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 手机号登录
$.get_loginTel = (req, res) => {
    let {mobile, code} = req.query;
    userService.loginTel(mobile, code).then((data) => {
        req.session.client_login_info = data;

        let update_time = helper.now();
        let client_ip = helper.getClientIP(req);
        let client_ip_address = '';
        if (client_ip) {
            const res = query.search(client_ip) || {province: '', city: ''};
            client_ip_address = `${res.province ? res.province : ''} ${res.city}`;
        }

        db().md_user.update({
            last_login_time: update_time,
            last_client_ip: client_ip,
            last_client_ip_address: client_ip_address,
        }, {where: {id: data.id}});
        db().md_user_login_log.create({
            id: helper.uuid(),
            user_id: data.id,
            client_ip: client_ip,
            client_ip_address: client_ip_address,
        });

        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

$.post_loginThird = (req, res) => {
    let {mobile, code, ext} = req.body;
    userService.loginThird(mobile, code, ext).then((data) => {
        req.session.client_login_info = data;

        let update_time = helper.now();
        let client_ip = helper.getClientIP(req);
        let client_ip_address = '';
        if (client_ip) {
            const res = query.search(client_ip) || {province: '', city: ''};
            client_ip_address = `${res.province ? res.province : ''} ${res.city}`;
        }

        db().md_user.update({
            last_login_time: update_time,
            last_client_ip: client_ip,
            last_client_ip_address: client_ip_address,
        }, {where: {id: data.id}});
        db().md_user_login_log.create({
            id: helper.uuid(),
            user_id: data.id,
            client_ip: client_ip,
            client_ip_address: client_ip_address,
        });

        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 退出
$.get_logout = (req, res) => {
    req.session.client_login_info = null;
    res.jsonWrap(true);
};

// 检查手机号
$.get_checkMobile = (req, res) => {
    let {mobile} = req.query;
    userService.checkMobile(mobile || '').then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 注册
$.get_register = (req, res) => {
    let {mobile, code, password, password_confirm} = req.query;
    userService.register(mobile, code, password, password_confirm).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 找回密码
$.get_forgetPassword = (req, res) => {
    let {mobile, code, password, password_confirm} = req.query;

    userService.forgetPassword(mobile, code, password, password_confirm).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 添加至收藏
$.post_addToFavorite = [sessionFilter, (req, res) => {
    userService.addToFavorite(req.session.client_login_info.id, req.body.id || '').then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
}];

// 删除收藏
$.post_deleteFavorite = [sessionFilter, (req, res) => {
    userService.deleteFavorite(req.session.client_login_info.id, req.body.id || '').then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
}];

// 获取收藏列表
$.get_favoriteList = [sessionFilter, (req, res) => {
    let pageLimit = pager.requestFilter(req);
    let args = req.query || {};
    args.user_id = req.session.client_login_info.id;

    userService.favoriteList(pageLimit.page, pageLimit.limit, args).then((data) => {
        data.detailUrl = configure.get('pushHistory').detailUrl;
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
}];

// 修改用户信息
$.post_updateUserInfo = [sessionFilter, (req, res) => {
    let args = {
        id: req.session.client_login_info.id,
        name: req.body.name || '',
        nickname: req.body.nickname || '',
        job: req.body.job || '',
        company_name: req.body.company_name || '',
        avatar: req.body.avatar || '',
        email: req.body.email || '',
        sex: req.body.sex || 1,
    };

    userService.saveUser(args).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
}];

// 获取收藏列表
$.get_couponList = [sessionFilter, (req, res) => {
    let pageLimit = pager.requestFilter(req);
    let args = req.query || {};
    args.user_id = req.session.client_login_info.id;

    userService.couponList(pageLimit.page, pageLimit.limit, args).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
}];

// 个人中心统计数据
$.get_stat = [sessionFilter, (req, res) => {
    userService.stat(req.session.client_login_info.id).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
}];

// qq登录授权
$.get_qqAuthPage = (req, res) => {
    thirdLoginService.qqAuthPage().then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// wx登录授权
$.get_wxAuthPage = (req, res) => {
    thirdLoginService.wechatAuthPage().then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 用户信息
$.post_authUser = (req, res) => {
    thirdLoginService.getUserInfo(req.body.code || '', req.body.state || '', req).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};

// 随机客服
$.get_randomUser = (req, res) => {
    userService.randomUser(req.query || {}).then((data) => {
        res.jsonWrap(data);
    }).catch((e) => {
        log4js.error(e);
        res.jsonWrap(null, 1, e.message);
    });
};




